<!-- 颜色 -->
<template>
  <view>
    <hx-navbar ref="hxnb" :config="config" @clickBtn="clickBtn">
      <view slot="bottom">
        <template>
          <view class="input-product">
            <u--input
              customStyle="height:100%;width: 90%;margin: auto;"
              placeholderStyle="color: #fff;"
              placeholder="搜索或添加颜色"
              border="none"
              color="#fff"
              shape="circle"
              v-model="params.data.keywords"
              @confirm="searchChange"
            >
              <clIcon
                slot="prefix"
                type="icon-sousuo_o"
                color="#fff"
                size="25"
              ></clIcon>
            </u--input>
          </view>
        </template>
      </view>
    </hx-navbar>
    <view class="u-page m-t-140">
      <view class="color-list">
        <view
          class="color-item flex flex-sb"
          @click="goRoute(item)"
          v-for="(item, index) in list"
          :key="index"
        >
          <!-- <liu-swipe-action ref="swipe" :index="index" @clickItem="clickItem"> -->
          <view class="color-number p-b-14">
            {{ item.colorNumber }} {{ item.color }}
          </view>
          <view class="content">
              <text v-if="selected(item) > 0">已选<text class="c-red">{{ selected(item) }}匹</text> </text> <text class="m-l-15 c-red" v-if="selectedMi(item) > 0"> {{selectedMi(item)}}米</text>
          </view>
          <!-- <view class="content" v-if="showCon()">
            <template>
              <text class="grey">可发货</text>
              <text>1匹 23米</text>
            </template>
            <template v-else>
              <text class="grey">暂无可发</text>
            </template>
          </view> -->

          <!-- </liu-swipe-action> -->
        </view>
      </view>
    </view>
    <!-- 添加颜色模态框 -->
    <u-popup
      class="u-pop"
      :show="show"
      :round="10"
      mode="center"
      :closeOnClickOverlay="false"
    >
      <view class="popup-view">
        <view class="title">
          {{ isEdit ? "编辑颜色" : "新增颜色" }}
        </view>
        <view class="form-view m-b-40">
          <view class="form-item">
            <view class="label"> 色号 </view>
            <view class="value">
              <u--input
                border="surround"
                v-model="addColorParams.colorNumber"
              ></u--input>
            </view>
          </view>
          <view class="form-item">
            <view class="label"> 颜色 </view>
            <view class="value">
              <u--input
                border="surround"
                v-model="addColorParams.color"
              ></u--input>
            </view>
          </view>
          <view class="form-item" @click="toColorSys">
            <view class="label"> 色系 </view>
            <view class="value">
              <u--input
                @focus="toColorSys"
                disabledColor="#fff"
                border="surround"
                v-model="addColorParams.colorSystemName"
                suffixIcon="arrow-down"
                suffixIconStyle="color: #909399"
              ></u--input>
            </view>
          </view>
          <view class="form-item" @click="toConverter">
            <view class="label"> 加工商 </view>
            <view class="value">
              <u--input
                border="surround"
                @focus="toConverter"
                disabledColor="#fff"
                v-model="addColorParams.processorName"
                suffixIcon="arrow-down"
                suffixIconStyle="color: #909399"
              ></u--input>
            </view>
          </view>
          <view class="form-item">
            <view class="label"> 起订量 </view>
            <view class="value">
              <u--input
                border="surround"
                v-model="addColorParams.startOrderQuantity"
              ></u--input>
            </view>
          </view>
        </view>
        <view class="bot-view flex flex-sa">
          <view class="btn" @click="onCencal"> 取消 </view>
          <view class="btn" @click="onBatch" v-if="!isEdit"> 批量新增 </view>
          <view class="btn" @click="onConfirm"> 确认 </view>
        </view>
      </view>
    </u-popup>
    <!-- 批量生成 -->
    <u-popup
      :show="batchShow"
      :round="10"
      :closeOnClickOverlay="false"
      mode="center"
    >
      <view class="popup-view">
        <view class="title"> 批量生成 </view>
        <view class="form-view m-b-40">
          <view class="form-item">
            <view class="label"> 色号 </view>
            <view class="value flex">
              <u--input
                border="surround"
                v-model="batchParams.startNumber"
              ></u--input>
              <text class="p-r-20 p-l-20">-</text>
              <u--input
                border="surround"
                v-model="batchParams.endNumber"
              ></u--input>
            </view>
          </view>
          <view class="form-item">
            <view class="label"> 前缀 </view>
            <view class="value">
              <u--input
                border="surround"
                v-model="batchParams.prefix"
              ></u--input>
            </view>
          </view>
          <view class="form-item">
            <view class="label"> 后缀 </view>
            <view class="value">
              <u--input
                border="surround"
                v-model="batchParams.suffix"
              ></u--input>
            </view>
          </view>
          <view class="form-item" @click="toColorSys">
            <view class="label"> 色系 </view>
            <view class="value">
              <u--input
                @focus="toColorSys"
                disabledColor="#fff"
                border="surround"
                v-model="colorSystem"
                suffixIcon="arrow-down"
                suffixIconStyle="color: #909399"
              ></u--input>
            </view>
          </view>
        </view>
        <view class="bot-view flex flex-sa">
          <view class="btn" @click="onBatchCencal"> 取消 </view>
          <view class="btn" @click="onBatchConfirm"> 确定 </view>
        </view>
      </view>
    </u-popup>
    <u-toast ref="uToast"></u-toast>
  </view>
</template>

<script>
import clIcon from "@/components/cl-icon/cl-icon.vue";
import {
  listBySpuId,
  deleteById,
  updateBatch,
  saveBatch,
  getById,
} from "@/apis/inventory/color";
export default {
  components: {
    clIcon,
  },
  data() {
    return {
      // 显示相同部分内容
      whiteList: ["return", "salesOrder"],
      config: {
        title: "选择颜色",
        color: "#ffffff",
        //背景颜色;参数一：透明度（0-1）;参数二：背景颜色（array则为线性渐变，string为单色背景）
        backgroundColor: [1, ["#409EFF", "#409EFF", "#60b4f6", "#60b4f6"]],
        rightButton: [
          {
            key: "btn1",
            icon: "&#xe727;",
            position: "left",
          },
        ],
      },
      // 颜色列表
      list: [],
      // 显示模态框
      show: false,
      value: "",
      params: {
        data: {
          spuId: "",
          keywords: "",
        },
        page: {
          current: 1,
          size: 999,
        },
      },
      // 新增颜色参数
      addColorParams: {
        colorNumber: "",
        color: "",
        colorSystemId: "",
        colorSystemName: "",
        processorId: "",
        processorName: "",
        startOrderQuantity: "",
        spuId: "",
      },
      // 是否显示批量生成弹框
      batchShow: false,
      batchParams: {
        startNumber: 12,
        endNumber: "",
        prefix: "",
        suffix: "#",
        colorSystemId: "",
      },
      // 色系
      colorSystem: "",
      isEdit: false,
      index: "",
      // 页面来源
      pageSource: "",
      djRowItem: {},
    };
  },
  computed: {},
  onLoad(opt) {
    this.pageSource = this.$Route.query.source || opt.socure;
    // 获取产品信息
    // 如果是采购单的过来的 我数据都在 this.$ls.get('cgdInformation') 里面存储的
    // if (this.pageSource == "cgd") {
    // 	const djRowItem = this.$getPageParams('djRowItem')
    // 	this.djRowItem = djRowItem
    // 	const { spuId, code, name } = djRowItem.list;
    // 	this.params.data.spuId = spuId;
    // 	this.addColorParams.spuId = spuId;
    // 	this.config.title = `${code} ${name}`
    // 	this.initData();
    // }
    // // 如果是采购单的过来的 我数据都在 this.$ls.get('cgdInformation') 里面存储的
    // if (this.pageSource == "xsd") {
    // 	const djRowItem = this.$getPageParams('djRowItem')
    // 	this.djRowItem = djRowItem
    // 	const { spuId, code, name } = djRowItem.list;
    // 	this.params.data.spuId = spuId;
    // 	this.addColorParams.spuId = spuId;
    // 	this.config.title = `${code} ${name}`
    // 	this.initData();
    // }
    // if (this.pageSource == "thjs") {
    // 	const djRowItem = this.$getPageParams('djRowItem')
    // 	this.djRowItem = djRowItem
    // 	const { spuId, code, name } = djRowItem.list;
    // 	this.params.data.spuId = spuId;
    // 	this.addColorParams.spuId = spuId;
    // 	this.config.title = `${code} ${name}`
    // 	this.initData();
    // }
    // if (this.pageSource == "khdd") {
    // 	const djRowItem = this.$getPageParams('djRowItem')
    // 	this.djRowItem = djRowItem
    // 	const { spuId, code, name } = djRowItem.list;
    // 	this.params.data.spuId = spuId;
    // 	this.addColorParams.spuId = spuId;
    // 	this.config.title = `${code} ${name}`
    // 	this.initData();
    // }
    // if (this.pageSource == "cgdreturn") {
    // 	const djRowItem = this.$getPageParams('djRowItem')
    // 	this.djRowItem = djRowItem
    // 	const { spuId, code, name } = djRowItem.list;
    // 	this.params.data.spuId = spuId;
    // 	this.addColorParams.spuId = spuId;
    // 	this.config.title = `${code} ${name}`
    // 	this.initData();
    // }
    // if (this.pageSource == "dbd") {
    // 	const djRowItem = this.$getPageParams('djRowItem')
    // 	this.djRowItem = djRowItem
    // 	const { spuId, code, name } = djRowItem.list;
    // 	this.params.data.spuId = spuId;
    // 	this.addColorParams.spuId = spuId;
    // 	this.config.title = `${code} ${name}`
    // 	this.initData();
    // }
    // if (this.pageSource == "dkc") {
    // 	this.params.data.spuId = this.$Route.query.spuId;
    // 	this.addColorParams.spuId = this.$Route.query.spuId;
    // 	this.initData();
    // }
  },
  onShow() {
    this.list = [];
    this.djRowItem = this.$getPageParams("djRowItem");
    const { spuId, code, name } = this.djRowItem.list;
    this.params.data.spuId = spuId;
    this.addColorParams.spuId = spuId;
    this.config.title = `${code} ${name}`;
    this.initData();
    // 获取色系数据
    uni.$on("on-color-system-data", (res) => {
      this.colorSystem = res.label;
      if (this.show) {
        this.addColorParams.colorSystemId = res.value;
        this.addColorParams.colorSystemName = res.label;
      } else if (this.batchShow) {
        this.batchParams.colorSystemId = res.value;
      }
      uni.$off("on-color-system-data");
    });
    // 获取加工商
    uni.$on("on-converter-data", (res) => {
      this.addColorParams.processorId = res.id;
      this.addColorParams.processorName = res.name;
      uni.$off("on-converter-data");
    });
  },
  methods: {
    // 查看当前获取的匹数
    selected(item) {
      let data = {};
      if (this.pageSource == "xsd") {
        data = this.$ls.get("xsdInformation");
      } else if (this.pageSource == "cgd") {
        data = this.$ls.get("cgdInformation");
      } else if (this.pageSource == "thjs") {
        data = this.$ls.get("thjsInformation");
      } else if (this.pageSource == "khdd") {
        data = this.$ls.get("khddInformation");
      } else if (this.pageSource == "cgdreturn") {
        data = this.$ls.get("cgdreturnInformation");
      } else if (this.pageSource == "dbd") {
        data = this.$ls.get("dbdInformation");
      }
      if (!data || data.productInformation.length == 0) {
        return 0;
      }
      return data.productInformation
        .filter((obj) => obj.colorId === item.id)
        .reduce((acc, obj) => {
          const count = Number(obj.piecesCount);
          return isNaN(count) ? acc : acc + count;
        }, 0);
    },
    // 查看当前获取的匹数
    selectedMi(item) {
      let data = {};
      if (this.pageSource == "xsd") {
        data = this.$ls.get("xsdInformation");
      } else if (this.pageSource == "cgd") {
        data = this.$ls.get("cgdInformation");
      } else if (this.pageSource == "thjs") {
        data = this.$ls.get("thjsInformation");
      } else if (this.pageSource == "khdd") {
        data = this.$ls.get("khddInformation");
      } else if (this.pageSource == "cgdreturn") {
        data = this.$ls.get("cgdreturnInformation");
      } else if (this.pageSource == "dbd") {
        data = this.$ls.get("dbdInformation");
      }
      if (!data || data.productInformation.length == 0) {
        return 0;
      }
      return data.productInformation
        .filter((obj) => obj.colorId === item.id)
        .reduce((acc, obj) => {
          const count = Number(obj.quantity);
          return isNaN(count) ? acc : acc + count;
        }, 0);
    },
    showCon() {
      return this.whiteList.includes(this.pageSource);
    },
    // 跳转加工商
    toConverter() {
      uni.navigateTo({
        url: "/pages/application/pages/cloth/converter/index?type=list",
      });
    },
    goRoute(val) {
      let { type } = this.$Route.query;
      if (type == "list") {
        setTimeout(() => {
          uni.$emit("on-color-data", val);
        }, 300);
        uni.navigateBack();

        return;
      }
      // 如果djRowItem.info.isEcho 那么则是需要编辑的 否则就是新增
      if (this.djRowItem.info.isEcho) {
        // const djRowItem = this.$getPageParams('djRowItem')
        let dataItem = this.$ls.get("xsdInformation");
        // this.$ls.set('xsdInformation', dataItem)
      } else {
        let item = this.$getPageParams("djRowItem");
        item.list.colorNumber = val.colorNumber;
        item.list.color = val.color;
        item.list.colorId = val.id;
        item.list.auxiliaryColorNumber = val.auxiliaryColorNumber;
        item.list.auxiliaryColor = val.auxiliaryColor;
        this.$setPageParams("djRowItem", {
          list: item.list,
          info: {
            isEcho: false,
            index: 0,
          },
          likeList: item.likeList,
        });
      }

      uni.redirectTo({
        url: `/pages/application/pages/cloth/customer-product-billing/index?source=${this.pageSource}`,
      });
    },
    // 获取数据
    initData() {
      // 1. 查询列表信息
      listBySpuId(this.params).then((res) => {
        if (!res.flag) return;
        this.list = res.data.records;
      });
    },
    scrolltolower() {},
    searchChange() {
      this.list = [];
      this.params.page.current = 1;
      this.initData();
    },
    clickBtn(item) {
      if (item.key === "btn1") {
        this.show = true;
        this.isEdit = false;
        this.colorSystem = "";
      }
    },
    // 取消
    onCencal() {
      this.addColorParams = {
        colorNumber: "",
        color: "",
        colorSystemId: "",
        colorSystemName: "",
        processorId: "",
        processorName: "",
        startOrderQuantity: "",
        spuId: "",
      };
      this.show = false;
      this.onReset();
      // this.$refs.swipe[this.index] && this.$refs.swipe[this.index].reset();
    },
    // 确认新增
    onConfirm() {
      if (!this.addColorParams.colorNumber) {
        uni.showToast({
          title: "色号不能为空",
          icon: "none",
        });
        return;
      }
      if (this.isEdit) {
        updateBatch([this.addColorParams]).then((res) => {
          if (!res.flag) return;
          this.onCencal();
          uni.showToast({
            title: "编辑成功",
          });
          this.initData();
        });
      } else {
        saveBatch([this.addColorParams]).then((res) => {
          if (!res.flag) return;
          this.onCencal();
          this.$refs.uToast.show({
            type: "success",
            title: "",
            message: "添加成功",
          });
          this.initData();
        });
      }
    },
    // 打开批量新增
    onBatch() {
      this.batchShow = true;
      this.show = false;
      this.colorSystem = "";
    },
    // 批量取消
    onBatchCencal() {
      this.batchShow = false;
      this.onReset();
    },
    // 批量确定
    onBatchConfirm() {
      const dataObj = this.batchParams || {};
      const startNumber = dataObj.startNumber;
      const endNumber = dataObj.endNumber;
      const prefix = dataObj.prefix || "";
      const suffix = dataObj.suffix || "";
      const colorSystemId = dataObj.colorSystemId;
      const colorSystemName = this.colorSystem;
      const tableData = [];
      for (let i = startNumber; i <= endNumber; i++) {
        const colorNumber = `${prefix}${i}${suffix}`;
        const row = {
          colorNumber,
          colorSystemId,
          colorSystemName,
          spuId: this.addColorParams.spuId,
        };
        tableData.push(row);
      }
      saveBatch(tableData).then((res) => {
        if (!res.flag) return;
        this.onBatchCencal();
        this.$refs.uToast.show({
          type: "success",
          title: "",
          message: "添加成功",
        });
        this.initData();
      });
    },
    // 跳转色系
    toColorSys() {
      this.$Router.push({
        name: "inventoryQuantityColorSys",
      });
    },
    // 重置
    onReset() {
      this.batchParams = {
        startNumber: 12,
        endNumber: "",
        prefix: "",
        suffix: "#",
        colorSystemId: "",
      };
      this.addColorParams.colorSystemId = "";
    },
    clickItem(val) {
      let { index, id } = val;
      let _thisData = this.list[index];
      this.index = index;
      if (id == "1") {
        // 编辑
        this.show = true;
        this.isEdit = true;
        getById(_thisData.id).then((res) => {
          if (!res.flag) return;
          this.addColorParams = res.data;
        });
        // this.params.isDefault = _thisData.isDefault;
      } else {
        // 删除
        uni.showModal({
          content: "确定是否删除当前颜色？",
          success: (res) => {
            if (res.confirm) {
              deleteById(_thisData.id).then((res) => {
                if (!res.flag) return;
                uni.showToast({
                  title: "删除成功",
                });
                this.initData();
              });
            } else {
              this.$refs.swipe[this.index].reset();
            }
          },
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.input-product {
  width: 95%;
  padding: 0 20upx;
  margin: 30upx auto;
  border: 1px solid #fff;
  border-radius: 50upx;
  height: 70upx;
  line-height: 70upx;
  color: #fff;
  display: flex;
}

.color-list {
  .color-item {
    font-size: 28rpx;
    padding: 20rpx 40rpx;
    margin-bottom: 1rpx;
    background: #fff;
  }
}
</style>
